<?php

namespace fanletter\manager;

/**
 * 
 * manages the Newsletter objects
 * @author Evan
 *
 */
use fanletter\library\SQLConnection;

use fanletter\model\Newsletter;

class NewsletterManager
{
	private static $instance;
	private $newsletter;
	
	/**
	 * 
	 * @return NewsletterManager
	 */
	public static function getInstance()
	{
		if (self::$instance === NULL)
		{
			self::$instance = new self;
		}
		return self::$instance;
	}
	
	public function getNewsletterById($id)
	{
		if (is_array($this->newsletter))
		{
			if (isset($this->newsletter[$id]))
			{
				return $this->newsletter[$id];
			}
		}
		return $this->getNewsletterFromDbById($id);
	}
	
	private function getNewsletterFromDbById($id)
	{
		$dbh = SQLConnection::getInstance()->getDBReference();
		$newsletterStatement = $dbh->prepare("SELECT * FROM fanletter_newsletter WHERE id = ?");
		$newsletterStatement->execute(array($id));
		$newsletterData = $newsletterStatement->fetch(\PDO::FETCH_ASSOC);
		if (is_array($newsletterData))
		{
			$this->newsletter[$id] = new Newsletter($id, $newsletterData['title'], \DateTime::createFromFormat("U", $newsletterData['date']), $newsletterData['sent'], $newsletterData['style']);
			return $this->newsletter[$id];
		}
		return FALSE;
	}
	
	public function getNewsletterBetweenIdXY($idX, $idY)
	{
		$returnArray = array();

		// Check, if array exists and check the contents
		if (is_array($this->newsletter))
		{
			$i = idX;
			$continue = true;
			while ($continue && $i <= $idY)
			{
				// Is an element missing? Then fetch all the data from here
				if ($isset($this->newsletter[$i]))
				{
					$returnArray[] = $this->newsletter[$i];
				}
				else 
				{
					array_push($returnArray, $this->getNewsletterFromDbBetweenIdXY($i, $idY));
					$continue = FALSE;
				}
				$i++;
			}
		}
		return $returnArray;
	}
	
	private function getNewsletterFromDbBetweenIdXY($idX, $idY)
	{
		$returnArray = array();
		$dbh = SQLConnection::getInstance()->getDBReference();
		$newsletterStatement = $dbh->prepare("SELECT * FROM fanletter_newsletter WHERE id BETWEEN ? AND ?");
		$newsletterStatement->execute(array($idX, $idY));
		while ($newsletterData = $newsletterStatement->fetch(\PDO::FETCH_ASSOC))
		{
			$this->newsletter[$newsletterData['id']] = new Newsletter($newsletterData['id'], $newsletterData['title'], \DateTime::createFromFormat("U", $newsletterData['date']), $newsletterData['sent'], $newsletterData['style']);
			$returnArray = $this->newsletter[$newsletterData['id']];
		}
		return $returnArray;
	}
	
	public function getNewsletterByDatePeriod(\DateTime $dateStart, \DateTime $dateEnd)
	{
		//TODO: Evan: Check DateTime-Class
	}
	
	public function getContentByNewsletterId($id)
	{
		ContentManager::getInstance()->getContentByNewsletterId($id);
	}
	
}
